/// ===========================================================================
/// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
/// KIND, WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
/// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
/// PURPOSE.
/// ===========================================================================
/// 
/// Project:        MOSS Usage Tools
/// Authors:        Leonid Lyublinski (leonidly@microsoft.com)
///                 Rita Zhang (ritazh@microsoft.com)
/// Company:        Microsoft Services
/// Date:           05/04/2008  
/// Version:        1.0
///
/// ===========================================================================

using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.Threading;
using System.Collections;
using System.Diagnostics;
using System.Text;
using System.IO;

namespace Microsoft.SharePoint.Administration.UsageSettings
{
    /// <summary>
    /// Define a new SharePoint Timer Service Job
    /// </summary>
    public class CustomTimerJob : SPJobDefinition
    {
        #region Private Fields

        #endregion

        /// <summary>
        /// Initializes a new instance of the CustomTimerJob class.
        /// </summary>
        public CustomTimerJob()
            : base()
        {
        }

        /// <summary>
        /// Initializes a new instance of the CustomTimerJob class.
        /// </summary>
        /// <param name="jobName">Name of the job.</param>
        /// <param name="service">The service.</param>
        /// <param name="server">The server.</param>
        /// <param name="targetType">Type of the target.</param>
        public CustomTimerJob(string jobName, SPService service)
            : base(jobName, service, null, SPJobLockType.None)//Locks the content database before processing. 
        {
        }

        /// <summary>
        /// Initializes a new instance of the CustomTimerJob class.
        /// </summary>
        /// <param name="jobName">Name of the job.</param>
        /// <param name="webApplication">The web application.</param>
        public CustomTimerJob(string jobName, SPWebApplication webApplication, SPServer server, SPJobLockType targetType)
            : base(jobName, webApplication, server, targetType)
        {
        }

        /// <summary>
        /// Executes the specified content db id.
        /// </summary>
        /// <param name="contentDbId">The content db id.</param>
        public override void Execute(Guid contentDbId)
        {
            string csvFileLocation = string.Empty;

            try
            {
                //Gets timer job custom properties
                if (this.Properties.ContainsKey(Common.Resource.UsageLogProcessorProperties))
                {
                    csvFileLocation = this.Properties[Common.Resource.UsageLogProcessorProperties].ToString();
                    //if file location entered is invalid, set it to default and log error
                    if(csvFileLocation == string.Empty && !Directory.Exists(csvFileLocation))
                    {
                        //logMessage("Usage Log Processor Timer Job will use default log location due to invalid log directory input: " + csvFileLocation, EventLogEntryType.Warning);
                        csvFileLocation = string.Empty;

                    }
                }
                
                SPWebService webservice = null;
                webservice = SPWebService.AdministrationService;
                if (webservice != null)
                {
                    
                    string logFilesDirectory = null;
                    logFilesDirectory = webservice.UsageSettings.LogFilesDirectory;
                    if (logFilesDirectory != null)
                    {
                        string searchPattern = Common.Resource.FileSearchPattern;
                        string excelFileName = Common.Resource.ExcelFileName;
                        
                        Parser parser = new Parser();
                        string[] logs = Directory.GetFiles(logFilesDirectory, searchPattern, SearchOption.AllDirectories);
                        
                        if (csvFileLocation == string.Empty)
                        {
                            csvFileLocation = logFilesDirectory + Common.Resource.UsageDir + excelFileName;
                        }
                        else
                        {
                            csvFileLocation = csvFileLocation + Common.Resource.Slash + excelFileName;
                        }
                        bool fileExists = File.Exists(csvFileLocation);
                        ///TODO: For now, delete old then create a new file
                        ///need to append only new data from lastReadTime
                        if (fileExists)
                        {
                            File.Delete(csvFileLocation);
                        }

                        foreach (string log in logs)
                        {
                            parser.ConvertToCSVFile(log, csvFileLocation);
                        }
                    }
                    else
                    {
                        logMessage(Common.Resource.ErrorMsgCannotDetectFileLocation, EventLogEntryType.Warning);
                    }
                }
                
            }
            catch (Exception e)
            {
                logMessage(Common.Resource.AppLogName + e.StackTrace, EventLogEntryType.Warning);
            }
           
        }

        private static void logMessage(string message, EventLogEntryType type)
        {
          
            if (!EventLog.SourceExists(Common.Resource.AppLogName))
                EventLog.CreateEventSource(Common.Resource.AppLogName, "Application");
            EventLog.WriteEntry(Common.Resource.AppLogName, message, type);
             

        }

       
    }
        
   
}